import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import { Models } from '@/common/typings/modle'
import regexp from '@/common/utils/regexp'
import { ParameterException, Success } from '@/core/HttpException'
import { getMobileValidateCode, smsCodeIsOk } from '@/common/utils/utils'
import { sendCode } from '@/common/utils/mobile.utils'
import { getSmsCodeInterval, saveSmsCode, saveSmsCodeInterval } from '@/server/redis'
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/mobile`,
})
router.post('/send', async (ctx: Models.Ctx) => {
  const { mobile, smsCode } = ctx.request.body as any
  if (!regexp.mobile.test(mobile)) {
    throw new ParameterException({ msg: 'mobile 格式不正确' })
  }
  smsCodeIsOk(ctx, smsCode)
  // 发送短信之前，需要验证，是否处于间隔状态
  const res = await getSmsCodeInterval(mobile)
  if (res.results) {
    const now = Date.now()
    const diff = Math.ceil((now - res.results) / 1000)
    throw new Success({ data: 60 - diff, errorCode: -4 })
  }
  const validateCode = getMobileValidateCode()
  await sendCode({ mobile, code: validateCode })
  // 保存发送的验证码
  await saveSmsCode(mobile, validateCode)
  await saveSmsCodeInterval(mobile)
  throw new Success()
})
export default router
